import * as jose from 'jose';
import type { User } from "../../types";

const config = useRuntimeConfig();
// 配置检查jwtExpiresIn、jwtSecret是否存在
if (!config.jwtExpiresIn || !config.jwtSecret) {
  throw new Error('env jwtExpiresIn or jwtSecret is not defined');
}
// 令牌有效期，优先使用环境变量
const JWT_EXPIRES_IN = parseInt(config.jwtExpiresIn);

// 将密钥转换为 Uint8Array 格式
const getSecretKey = () => new TextEncoder().encode(config.jwtSecret);

/**
 * 生成JWT令牌
 * @param {User} payload 令牌载荷数据
 * @returns {Promise<string>} JWT令牌
 */
export async function generateToken(payload: User): Promise<string> {
  const secretKey = getSecretKey();
  
  // 计算过期时间
  const exp = Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN;
  
  // 创建JWT
  return await new jose.SignJWT({ ...payload })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime(exp)
    .setIssuedAt()
    .sign(secretKey);
}

/**
 * 验证JWT令牌
 * @param {string} token JWT令牌
 * @returns {Promise<User|null>} 解码后的载荷或null
 */
export async function verifyToken(token: string): Promise<User | null> {
  try {
    const secretKey = getSecretKey();
    const { payload } = await jose.jwtVerify(token, secretKey);
    return payload as unknown as User;
  } catch (error: any) {
    console.error("验证令牌失败:", error?.message);
    return null;
  }
}
